#include "SAX2SceneHandler.h"

SAX2SceneHandler::SAX2SceneHandler(void)
{
}

SAX2SceneHandler::~SAX2SceneHandler(void)
{
}

void SAX2SceneHandler::startElement(const XMLCh* const uri, const XMLCh* const localname,
		const XMLCh* const qname, const Attributes& attrs)
{
	string elementName(XMLString::transcode(localname));
	string attributeName;
	string attributeValue;
	SceneObject* sceneObject;
	if (elementName.compare("scene")==0)
	{
		attributeValue = getSceneAttribute("name", attrs);
		scene->setName(attributeValue);
	}
	else if (elementName.compare("image")==0)
	{
		attributeValue = getSceneAttribute("path", attrs);
		scene->setBackgroundPath(attributeValue);
	}
	else if (elementName.compare("object")==0)
	{
		attributeValue = getSceneAttribute("name", attrs);
		std::string name = attributeValue;
		attributeValue = getSceneAttribute("x_coordinate", attrs);
		int x_coordinate = toInteger(attributeValue);
		attributeValue = getSceneAttribute("y_coordinate", attrs);
		int y_coordinate = toInteger(attributeValue);
		attributeValue = getSceneAttribute("width", attrs);
		int width = toInteger(attributeValue);
		attributeValue = getSceneAttribute("height", attrs);
		int height = toInteger(attributeValue);
		attributeValue = getSceneAttribute("type", attrs);
		int type = toInteger(attributeValue);
		switch(type){
		case(SCENEOBJECT):{
			sceneObject = new SceneObject(x_coordinate + scene->getXCoordinate(), y_coordinate + scene->getYCoordinate(), name);
						  }break;
		case(MINE):{
			sceneObject = new Mine(x_coordinate + scene->getXCoordinate(), y_coordinate + scene->getYCoordinate(), 0);
					}break;
		default:sceneObject = new SceneObject(x_coordinate + scene->getXCoordinate(), y_coordinate + scene->getYCoordinate(), name);
			break;
		}
		
		
		try
		{
			sceneObject->loadSurface();
			scene->addObject(sceneObject);
		}
		catch (SDL_Exception &ex)
		{
				delete sceneObject;
		}

	}
}


void SAX2SceneHandler::setScene(Scene* scene)
{
	this->scene = scene;
}

string SAX2SceneHandler::getSceneAttribute(const string attrNameToFind, const Attributes& attrs)
{
	string attributeName;
	string attributeValue = "";
	XMLSize_t length = attrs.getLength();
	for (int i=0; i<length && (attributeValue.compare("")==0); i++)
	{
		attributeName = XMLString::transcode(attrs.getLocalName(i));
		if (areEqualStrings(attributeName, attrNameToFind))
		{
			attributeValue.append(XMLString::transcode(attrs.getValue(i)));
		}
	}
	return attributeValue;
}

int SAX2SceneHandler::toInteger(string str)
{
	int intValue = 0;
	stringstream ss(str);
	ss >> intValue;
	return intValue;
}

bool SAX2SceneHandler::areEqualStrings(string s1, string s2)
{
	bool result = false;
	if (s1.compare(s2)==0)
	{
		result = true;
	}
	return result;
}
